extends Node2D

## 楼层管理器
class_name LevelManager

## 当前测数
var _level : int = 1:
	set(value):
		_level = value
		emit_signal("level_changed", value)

## 游戏玩家
@onready var player: Player = $"Player"

## 楼层数据
var _level_data : Dictionary = {}

## 楼层变更通知
signal level_changed(level)

## 保存游戏数据到指定槽位
func save_data(slot: int = 0):
	self._refresh_level_data()
	var game_data = {
		"level": _level,
		"level_data": _level_data,
		"player": player.get_data()
	}
	var file = FileAccess.open("user://mota_%d.dat" % [slot], FileAccess.WRITE)
	if file == null:
		var file_err = FileAccess.get_open_error()
		$"HUD".show_toast("存档失败错误码： %s" % [str(file_err)])
		return
	file.store_string(JSON.stringify(game_data))
	$"HUD".show_toast("存档成功")

## 从指定槽位加载游戏数据 
func load_data(slot: int = 0):
	var file = FileAccess.open("user://mota_%d.dat" % [slot], FileAccess.READ)
	if file == null:
		var file_err = FileAccess.get_open_error()
		$"HUD".show_toast("读档失败错误码： %s" % [str(file_err)])
		return
	var game_data = JSON.parse_string(file.get_as_text())
	if game_data == null:
		$"HUD".show_toast("解析存档失败")
		return
	player.set_data(game_data["player"])
	for level in game_data["level_data"]:
		self._level_data[int(level)] = game_data["level_data"][level]
	self._refresh_level_scene(game_data["level"], true)
	self._level = game_data["level"]
	
## 设置楼层
func set_level(new_level: int):
	self._refresh_level_scene(new_level)
	self._level = new_level

## 获取楼层
func get_level() -> int:
	return _level

## 获取当前楼层节点
func get_current_level_node() -> LevelMap:
	return get_node("/root/LevelManager/Level%d" % [_level])

## 刷新楼层场景
func _refresh_level_scene(new_level: int, skip_store = false):
	# 保存当前楼层数据
	var level_node = self._refresh_level_data(skip_store)
	if level_node != null:
		level_node.queue_free()
	# 加载新场景和数据
	var new_level_node = load("res://src/level/levels/level_%d.tscn" % [new_level]).instantiate() as TileMap
	new_level_node.name = "Level%d" % [new_level]
	if _level_data.has(new_level):
		new_level_node.set_data(_level_data[new_level])
	self.add_child(new_level_node)
	self.move_child(new_level_node,%"Player".get_index())

## 刷新楼层数据
func _refresh_level_data(skip_store = false):
	var level_node = self.get_current_level_node()
	if level_node == null:
		return
	if level_node.is_connected("child_exiting_tree", level_node._on_child_exiting_tree.bind()):
		level_node.disconnect("child_exiting_tree", level_node._on_child_exiting_tree.bind())
	if not skip_store:
		self._level_data[_level] = level_node.get_data()
	return level_node

